import { Request, Response, NextFunction } from 'express'
import { validationResult } from 'express-validator'
import { createError } from './errorHandler'

export const handleValidationErrors = (req: Request, res: Response, next: NextFunction) => {
  const errors = validationResult(req)
  
  if (!errors.isEmpty()) {
    const errorMessages = errors.array().map(error => ({
      field: error.type === 'field' ? error.path : 'unknown',
      message: error.msg
    }))
    
    throw createError(
      'Validation failed',
      400,
      { validationErrors: errorMessages }
    )
  }
  
  next()
}

export const validatePagination = (req: Request, res: Response, next: NextFunction) => {
  const { page = 1, limit = 10 } = req.query
  
  const pageNum = parseInt(page as string)
  const limitNum = parseInt(limit as string)
  
  if (isNaN(pageNum) || pageNum < 1) {
    throw createError('Page must be a positive integer', 400)
  }
  
  if (isNaN(limitNum) || limitNum < 1 || limitNum > 100) {
    throw createError('Limit must be between 1 and 100', 400)
  }
  
  req.query.page = pageNum
  req.query.limit = limitNum
  
  next()
}